package com.wp.filter;

import com.alibaba.fastjson.JSON;
import com.wp.util.JwtUtil;
import com.wp.vo.Result;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: WangPeng
 * @createTime: 2023/01/04 19:31
 * @description:
 * @version: v1.0
 */
@Component
public class MyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //设置编码
        response.setContentType("json/application;charset=utf-8");
        //获取请求地址与请求方式
        String path = request.getRequestURI();
        String method = request.getMethod();
        //如果请求路径是"/login"且是post请求直接放行
        if ("POST".equals(method) && "/login".equals(path)){
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头中的token信息
        String token = request.getHeader("token");
        if (token != null && JwtUtil.verifyToken(token)){
            //解析token令牌
            Map<String, Object> map = JwtUtil.decodeJWT(token);
            //获取登录时保存在token中的用户名，以及用户具有的权限
            String username = (String) map.get("username");
            List<String> list = (List<String>) map.get("authorities");
            //把用户权限转换成List类型
            List<SimpleGrantedAuthority> authorityList = list.stream().map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
            //把token中的用户信息设置在上下文中继续向后传递
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorityList);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            filterChain.doFilter(request, response);
        }else {
            PrintWriter writer = response.getWriter();
            Result result = new Result(401,"未登录");
            String jsonString = JSON.toJSONString(result);
            writer.println(jsonString);
            writer.flush();
            writer.close();
        }
    }
}
